// 获取当前用户的菜单信息,封装为一个工具类
import {
	postRequest
} from './api'
//导出
export const initMenu = (router, store) => {
	//判断,如果菜单信息已经获取到,就直接退出
	if (store.state.routes.length > 0) {
		return;
	}
	//没有数据,获取数据库中的数据,
	//获取当前登录用户的权限信息,并且动态拼接出来路由的格式
	let a = sessionStorage.getItem("user");
	if (a && a !== undefined) {
		let userObj = JSON.parse(a);
		postRequest("/tMenu/queryTMenuByAdminId/" + userObj.id).then(resp => {
			if (resp) {
				//格式化Router
				let fmtRoutes = formatRoutes(resp.data.menuList);
				//添加到路由
				router.addRoutes(fmtRoutes);
				console.log("=======" + JSON.stringify(fmtRoutes));
				//将数据存入vuex中
				store.commit('initRouters', fmtRoutes);
			}
		})
	}
}
export const formatRoutes = (routes) => {
	let fmtRoutes = [];
	routes.forEach(router => {
		let {
			id,
			path,
			component,
			name,
			iconCls,
			children
		} = router;
		if (children && children instanceof Array) {
			//递归
			children = formatRoutes(children);
		}
		let fmRouter = {
			id: id,
			path: path,
			name: name,
			iconCls: iconCls,
			children: children,
			component(resolve) {
				if (component.startsWith("Home")) {
					require(['@/views/Main.vue'], resolve);
				} else {
					require(['@/components' + component + '.vue'], resolve);
				}
			}
		}
		fmtRoutes.push(fmRouter);
	});
	return fmtRoutes;
}